/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.classloader

import java.net.URL
import java.net.URLClassLoader
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.LoggerFactory

@Accessors
class FigClassLoader extends URLClassLoader {
	val static LOG = LoggerFactory.getLogger(FigClassLoader);
	Class<?> zlass = null;
	String zlassName = "";

	new() {
		super(#[])
	}

	def register(String name, byte[] bytes) {
		this.zlassName = name;
		this.zlass = super.defineClass(name, bytes, 0, bytes.length);
	}

	def register(String name, Class<?> zlass) {
		this.zlassName = zlass.name;
		this.zlass = zlass;
	}

	def register(Class<?> zlass) {
		this.zlassName = zlass.name;
		this.zlass = zlass;
	}

	def loadJar(String jarPath) {
		try {
			var sb = new StringBuffer("jar:file:/")
			sb.append(jarPath)
			sb.append("!/")
			super.addURL(new URL(sb.toString()));
		} catch (Exception e) {
			LOG.error("Failed to cache plugin JAR file", e)
		}
	}

	override findClass(String name) {
		var fig = new FigClassLoaderManage();
		var zlass = fig.get(name);
		if (zlass !== null) {
			return zlass.loadClass(name);
		}else{
			return System.classLoader.loadClass(name);
		}
	}
}
